import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:delivery_application/common/extension.dart';
import 'package:delivery_application/common/globs.dart';
import 'package:delivery_application/common/service_call.dart';
import 'package:delivery_application/common_widget/round_button.dart';
import 'package:delivery_application/common_widget/round_textfield.dart';
import 'package:delivery_application/view/home/home_page.dart';
import 'package:delivery_application/view/home/start_deliver.dart';
import 'package:delivery_application/view/login/login_view.dart';
import 'package:delivery_application/view/login/otp_view.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SignUpView extends StatefulWidget {
  const SignUpView({super.key});

  @override
  State<SignUpView> createState() => _SignUpViewState();
}

class _SignUpViewState extends State<SignUpView> {
  TextEditingController txtName = TextEditingController();
  TextEditingController txtMobile = TextEditingController();
  TextEditingController txtEmail = TextEditingController();
  TextEditingController txtPassword = TextEditingController();
  TextEditingController txtConfirmPassword = TextEditingController();

  @override
  Widget build(BuildContext context) {
    var media = MediaQuery.of(context).size; 
    return Scaffold(
      backgroundColor: Color(0xff00AEEE),
      body: SingleChildScrollView(
        child: Padding(
          
          padding: const EdgeInsets.symmetric(
              vertical: 20,
              horizontal:
                  25), 
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox(
                height: 30,
              ),
              Text(
                "注册",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 50,
                    fontWeight: FontWeight.w800),
              ),
              Text(
                "请完善您的信息",
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    fontWeight: FontWeight.w600),
              ),

              SizedBox(height: 40), 
              RoundTextfield(
                hintText: "昵称",
                controller: txtName,
              ),
              SizedBox(height: 30),
              RoundTextfield(
                hintText: "Email",
                controller: txtEmail,
                keyboardType: TextInputType.emailAddress,
              ),
              SizedBox(height: 30),
              RoundTextfield(
                hintText: "手机",
                controller: txtMobile,
                keyboardType: TextInputType.phone,
              ),
              SizedBox(height: 30),
              RoundTextfield(
                hintText: "密码",
                controller: txtPassword,
                obscureText: true,
              ),
              SizedBox(height: 30),
              RoundTextfield(
                hintText: "确认密码",
                controller: txtConfirmPassword,
                obscureText: true,
              ),
              SizedBox(height: 40),
              RoundButton(
                title: "注册",
                onPressed: btnSignUp,
              ),
              SizedBox(height: 20),
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  "已有账号？登录",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: 15,
                      fontWeight: FontWeight.w600),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 注册按钮点击事件
  void btnSignUp() async {
    // 表单验证
    if (txtName.text.isEmpty) {
      _showAlert("请输入昵称");
      return;
    }
    if (txtEmail.text.isEmpty || !txtEmail.text.contains('@')) {
      _showAlert("请输入有效的邮箱地址");
      return;
    }
    if (txtMobile.text.isEmpty) {
      _showAlert("请输入手机号码");
      return;
    }
    if (txtPassword.text.isEmpty) {
      _showAlert("请输入密码");
      return;
    }
    if (txtPassword.text != txtConfirmPassword.text) {
      _showAlert("两次输入的密码不一致");
      return;
    }
    
    // 获取本地存储
    final prefs = await SharedPreferences.getInstance();
    
    // 检查邮箱是否已注册
    final registeredEmails = prefs.getStringList('registeredEmails') ?? [];
    if (registeredEmails.contains(txtEmail.text)) {
      _showAlert("该邮箱已被注册");
      return;
    }
    
    // 保存用户信息
    await prefs.setString('userName', txtName.text);
    await prefs.setString('userPhone', txtMobile.text);
    await prefs.setString('userEmail', txtEmail.text);
    await prefs.setString('userPassword', txtPassword.text);
    
    // 添加到已注册邮箱列表
    registeredEmails.add(txtEmail.text);
    await prefs.setStringList('registeredEmails', registeredEmails);
    
    // 设置用户登录状态为已登录
    await prefs.setBool('isLoggedIn', true);
    
    // 显示注册成功提示
    _showSuccessDialog();
  }
  
  // 显示提示对话框
  void _showAlert(String message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text("提示"),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text("确定"),
          )
        ],
      ),
    );
  }
  
  // 显示注册成功对话框
  void _showSuccessDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text("注册成功"),
        content: Text("您已成功注册"),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 跳转到登录页面
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => const LoginView(),
                ),
              );
            },
            child: Text("去登录"),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              // 直接进入主页
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => const StartDeliver(),
                ),
              );
            },
            child: Text("直接进入"),
          )
        ],
      ),
    );
  }
}
